import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
} from "antd";
import { useSearchParams, Link } from "react-router-dom";
import { useEffect, useRef, useState } from "react";
import { http } from "@/utils";
//导入富文本编辑器
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { PlusOutlined } from "@ant-design/icons";
import "./index.scss";
//使用history进行页面跳转
import { history } from "@/utils/history";
import { useStore } from "@/store";
import { observer } from "mobx-react-lite";
const { Option } = Select;

const Publish = () => {
  // 频道列表仓库
  const { channelStore } = useStore();

  //封面图
  //通过useRef创建图片暂存仓库
  const fileListRef = useRef([]);
  //图片状态
  const [fileList, setFileList] = useState([]);
  // 上传成功回调
  const onUploadChange = (info) => {
    const fileList = info.fileList.map((file) => {
      if (file.response) {
        return {
          url: file.response.data.url,
        };
      }

      return file;
    });
    //存到图片仓库
    fileListRef.current = fileList;
    setFileList(fileList);
  };

  //封面type
  const [imgCount, setImgCount] = useState(1);
  const changeType = (e) => {
    const count = e.target.value;
    setImgCount(count);
    if (count === 1) {
      // 单图，只展示第一张
      const firstImg = fileListRef.current[0];
      setFileList(firstImg ? [firstImg] : []);
    } else if (count === 3) {
      // 三图，展示所有图片
      setFileList(fileListRef.current);
    }
  };

  //编辑功能
  //获取地址栏id参数，作为编辑文章作用
  const [params] = useSearchParams();
  const articleId = params.get("id");
  //根据文章id查文章
  //生成表单实例
  //也可以使用const form=useRef(null)，然后在Form组件上加上ref={form}
  const [form] = Form.useForm();
  useEffect(() => {
    async function getArticle() {
      const res = await http.get(`/mp/articles/${articleId}`);
      const { cover, ...formValue } = res.data;
      //动态设置表单数据：表单内容回填
      form.setFieldsValue({ ...formValue, type: cover.type });
      //格式化封面图片数据
      const imageList = cover.images.map((url) => ({ url }));
      //图片列表回填
      setFileList(imageList);
      //图片type回填
      setImgCount(cover.type);
      //图片暂存仓库回填
      fileListRef.current = imageList;
    }
    if (articleId) {
      // 拉取数据回显
      getArticle();
    }
  }, [articleId, form]);

  //提交表单
  const onFinish = async (values) => {
    // 数据的二次处理 重点是处理cover字段
    const { type, ...rest } = values;
    const _params = {
      ...rest,
      type,
      cover: {
        type,
        images: fileList.map((item) => item.url),
      },
    };
    if (articleId) {
      // 编辑
      await http.put(`/mp/articles/${articleId}?draft=false`, _params);
      message.success("编辑成功！");
      history.push(`/article`);
    } else {
      // 新增
      await http.post("/mp/articles?draft=false", _params);
      message.success("新增成功！");
      //重置表单
      form.resetFields();
    }
  };

  return (
    <div className='publish'>
      <Card
        title={
          <Breadcrumb separator='>'>
            <Breadcrumb.Item>
              <Link to='/'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {articleId ? "修改文章" : "发布文章"}
            </Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          // 注意：此处需要为富文本编辑表示的 content 文章内容设置默认值
          initialValues={{ type: 1, content: "" }}
          onFinish={onFinish}
          form={form}>
          <Form.Item
            label='标题'
            name='title'
            rules={[{ required: true, message: "请输入文章标题" }]}>
            <Input placeholder='请输入文章标题' style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label='频道'
            name='channel_id'
            rules={[{ required: true, message: "请选择文章频道" }]}>
            <Select placeholder='请选择文章频道' style={{ width: 400 }}>
              {channelStore.channels.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label='封面'>
            <Form.Item name='type'>
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 && (
              <Upload
                name='image'
                listType='picture-card'
                className='avatar-uploader'
                action='http://geek.itheima.net/v1_0/upload'
                fileList={fileList}
                onChange={onUploadChange}
                //上传图片的最大数量
                maxCount={imgCount}
                //是否允许多图选择
                multiple={imgCount > 1}
                showUploadList>
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label='内容'
            name='content'
            rules={[{ required: true, message: "请输入文章内容" }]}>
            <ReactQuill
              className='publish-quill'
              theme='snow'
              placeholder='请输入文章内容'></ReactQuill>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size='large' type='primary' htmlType='submit'>
                {articleId ? "修改文章" : "发布文章"}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default observer(Publish);
